<template>
  <article class="cmp cmp-encode-batch">
    <section class="content-wrapper">
      <div class="subtitle">文本模板</div>
      <section class="section-content">
        <textarea class="form-control" v-model="text" placeholder="请输入内容，变量用${}标识，如${1}" rows="4"></textarea>
      </section>
      <div class="subtitle">变量字典</div>
      <section class="section-content">
        <div class="row-flex" v-for="(v, i) in variableArr" :key="i">
          <div class="row-flex-prefix text-grey">{{ v }}</div>
          <div class="row-flex-main">
            <input class="form-control" v-model="variableDict[i]" placeholder="请输入变量字典，各项用逗号(,)分隔" />
          </div>
        </div>
        <div v-if="variableArr.length === 0" class="text-grey">暂无任何内容</div>
      </section>
      <div class="subtitle">生成结果</div>
      <section class="section-content text-grey">
        {{ resultTip || '暂无任何内容' }}
      </section>
    </section>
    <section class="btn-wrapper">
      <x-button type="primary" block @click="createCode">生 成</x-button>
    </section>
    <div class="canvas-wrapper" ref="canvasWrapper"></div>
  </article>
</template>

<script>
const path = global.require('path')
let JSZip = global.JSZip || null
let QRCode = global.QRCode || null
let JsBarcode = global.JsBarcode || null

export default {
  name: 'cmp-encode-batch',
  props: {
    codeType: {
      type: String,
      default: 'qrcode'
    }
  },
  data() {
    return {
      text: '',
      variableDict: [],
      textDict: {},
      zip: null,
      resultTip: '',
      chineseReg: /[\u2E80-\u2EFF\u2F00-\u2FDF\u3000-\u303F\u31C0-\u31EF\u3200-\u32FF\u3300-\u33FF\u3400-\u4DBF\u4DC0-\u4DFF\u4E00-\u9FBF\uF900-\uFAFF\uFE30-\uFE4F\uFF00-\uFFEF]+/g,
      loadingCount: 0,
    }
  },
  computed: {
    variableArr() {
      let result = []
      let regex = /\$\{(.+?)\}/g
      result = [...new Set(this.text.match(regex) || [])]
      return result
    }
  },
  watch: {
    variableArr(n, o) {
      if (n.length < o.length) {
        for (let i = n.length; i < o.length; i++) {
          this.variableDict[i] = ''
        }
      }
    }
  },
  beforeDestroy() {
  },
  methods: {
    // 整理数据
    getTextDict() {
      let textDict = { code: this.text }
      this.variableArr.forEach((v, i) => {
        if (!v) return
        let dictItem = (this.variableDict[i] || '').split(',')
        let _textDict = {}
        dictItem.forEach(v1 => {
          Object.keys(textDict).forEach(k2 => {
            let v2 = textDict[k2] || ''
            _textDict[`${k2}_${v1}`] = v2.replace(v, v1)
          })
        })
        textDict = { ..._textDict }
      })
      this.textDict = textDict
    },
    // 生成
    createCode() {
      if (this.loadingCount > 0) return
      this.getTextDict()
      if (Object.keys(this.textDict).length) {
        this.zip = new JSZip()
        let zipLocalUrl = path.join(this.$sharedObject('userDataPath'), `${this.codeType}_${Date.now()}.zip`)
        let doneCount = 0
        let dataUrlReg = /^\s*data:([a-z]+\/[a-z0-9-+.]+(;[a-z-]+=[a-z0-9-]+)?)?(;base64)?,/i
        Object.keys(this.textDict).forEach(k => {
          this.loadingCount++
          this.resultTip = '正在生成，请稍后...'
          if (this.codeType === 'barcode') {
            if (this.chineseReg.test(this.textDict[k])) {
              this.$toast('条形码不支持中文')
              doneCount++
              this.loadingCount--
              return
            }
            let imgObj = document.createElement('img')
            JsBarcode(imgObj, this.textDict[k], {
              format: 'code39',
              valid: (valid) => {
                if (!valid) console.error(valid)
                this.$nextTick(() => {
                  let url = imgObj.src
                  this.zip.file(`${k}.png`, (url || '').replace(dataUrlReg, ''), { base64: true })
                  doneCount++
                  this.loadingCount--
                  if (doneCount === Object.keys(this.textDict).length) {
                    this.zip.generateAsync({ type: "nodebuffer" }).then((content) => {
                      this.$sharedObject('jstoolsNode').writeFile(zipLocalUrl, content).then(() => {
                        this.resultTip = `条形码生成成功，位置：${zipLocalUrl}`
                      })
                    })
                  }
                })
              }
            })
          } else {
            QRCode.toDataURL(this.textDict[k], (err, url) => {
              if (err) console.error(err)
              let _url = decodeURIComponent(k)
              let _params = this.$jstools.getUrlParams(_url)
              this.zip.file(`${_params.textbookVersionName} ${_params.textbookVolumesName} ${_params.title || Date.now()}.png`, (url || '').replace(dataUrlReg, ''), { base64: true })
              doneCount++
              this.loadingCount--
              if (doneCount === Object.keys(this.textDict).length) {
                this.zip.generateAsync({ type: "nodebuffer" }).then((content) => {
                  this.$sharedObject('jstoolsNode').writeFile(zipLocalUrl, content).then(() => {
                    this.resultTip = `二维码生成成功，位置：${zipLocalUrl}`
                  })
                })
              }
            })
          }
        })
      }
    },
  }
}
</script>

<style scoped lang="less">
@import "~@/assets/css/_mixins.less";
@import "~@/assets/css/_color.less";

.cmp-encode-batch {
  height: calc(100% - 3em - 64px);
  display: flex;
  flex-direction: column;

  .content-wrapper {
    height: calc(100% - 1em - 38px);
    overflow: hidden auto;

    textarea {
      width: 100%;
      height: 10vw;
      font-size: 16px;
      padding: 1em;
      border: none;
      outline: 0;
      resize: none;
    }

    .subtitle {
      font-size: 16px;
      margin-top: 1em;
      margin-bottom: .5em;
    }

    .section-content {
      padding-left: 2em;
    }

    .row-flex-prefix {
      min-width: 50px;
    }
  }

  .btn-wrapper {
    margin-top: 1em;
  }

  .canvas-wrapper {
    position: fixed;
    top: 50%;
    left: -348px;
    width: 348px;
    height: 116px;
    visibility: hidden;
  }
}
</style>
